package com.ruoyi.serve.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.base.domain.Customer;
import com.ruoyi.base.domain.bo.CustomerBo;
import com.ruoyi.base.domain.bo.DisabilityTypeServiceItemBo;
import com.ruoyi.base.domain.vo.CustomerVo;
import com.ruoyi.base.domain.vo.DisabilityTypeServiceItemVo;
import com.ruoyi.base.service.ICustomerService;
import com.ruoyi.base.service.IDisabilityTypeServiceItemService;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.serve.domain.ServeTaskItem;
import com.ruoyi.serve.domain.bo.ServeTaskItemBo;
import com.ruoyi.serve.service.IServeTaskItemService;
import com.ruoyi.system.domain.vo.SysOssVo;
import com.ruoyi.system.service.ISysOssService;
import com.ruoyi.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import lombok.var;
import org.springframework.stereotype.Service;
import com.ruoyi.serve.domain.bo.ServeTaskBo;
import com.ruoyi.serve.domain.vo.ServeTaskVo;
import com.ruoyi.serve.domain.ServeTask;
import com.ruoyi.serve.mapper.ServeTaskMapper;
import com.ruoyi.serve.service.IServeTaskService;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 服务任务Service业务层处理
 *
 * @author ruoyi
 * @date 2022-11-03
 */
@RequiredArgsConstructor
@Service
public class ServeTaskServiceImpl implements IServeTaskService {

    private final ServeTaskMapper baseMapper;

    private final ICustomerService customerService;

    private final ISysUserService userService;

    private final IDisabilityTypeServiceItemService serviceItemService;

    private final IServeTaskItemService serveTaskItemService;

    /**
     * 查询服务任务
     */
    @Override
    public ServeTaskVo queryById(Long id){
        ServeTaskVo serveTaskVo = baseMapper.selectVoById(id);
        CustomerVo customerVo = customerService.queryById( serveTaskVo.getCustomerId());
        serveTaskVo.setCustomer(customerVo);
        //查询服务项目
        ServeTaskItemBo serveTaskItemBo = new ServeTaskItemBo();
        serveTaskItemBo.setTaskId(serveTaskVo.getId());
        serveTaskVo.setServeTaskItemVoList(serveTaskItemService.queryList(serveTaskItemBo));
        return serveTaskVo;
    }

    /**
     * 查询服务任务列表
     */
    @Override
    public TableDataInfo<ServeTaskVo> queryPageList(ServeTaskBo bo, PageQuery pageQuery) {
        if(StringUtils.isNotEmpty(bo.getUserPhonenumber())){
            SysUser user = userService.selectUserByPhonenumber(bo.getUserPhonenumber());
            if(user==null){
                return TableDataInfo.build();
            }
            bo.setUserId(user.getUserId());
        }
        Page<ServeTaskVo> result = baseMapper.selectTaskList(pageQuery.build(),bo);

        result.getRecords().stream().forEach(r->{
            //查询上次服务时间
            Date lastServeTime = baseMapper.getLastServeTime(r.getId());
            r.setLastServeTime(lastServeTime);
        });
        return TableDataInfo.build(result);
    }

    /**
     * 查询服务任务列表
     */
    @Override
    public List<ServeTaskVo> queryList(ServeTaskBo bo) {
        LambdaQueryWrapper<ServeTask> lqw = buildQueryWrapper(bo);
        return baseMapper.queryList(bo);
    }

    private LambdaQueryWrapper<ServeTask> buildQueryWrapper(ServeTaskBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ServeTask> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getUserId() != null, ServeTask::getUserId, bo.getUserId());
        lqw.eq(bo.getCustomerId() != null, ServeTask::getCustomerId, bo.getCustomerId());
        lqw.ge(bo.getBeginTime() != null, ServeTask::getBeginTime, bo.getBeginTime());
        lqw.le(bo.getEndTime() != null, ServeTask::getEndTime, bo.getEndTime());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), ServeTask::getStatus, bo.getStatus());

        lqw.orderByDesc(ServeTask::getCreateTime);
        return lqw;
    }

    /**
     * 新增服务任务
     */
    @Transactional
    @Override
    public Boolean insertByBo(ServeTaskBo bo) {
        //查询失能类型
        CustomerVo customer = customerService.queryById(bo.getCustomerId());

        //设置顾客姓名
       /* bo.setCustomerName(customer.getCustomerName());
        bo.setCustomerImg(customer.getCustomerImg());*/

        //设置员工姓名
        bo.setUserName(userService.selectUserById(bo.getUserId()).getNickName());
        //设置任务状态为未开始
        bo.setStatus("0");

        ServeTask add = BeanUtil.toBean(bo, ServeTask.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            //插入勾选的服务项目
            for(int i = 0;i < bo.getServiceItemIds().length;i++){
                long serviceItemId = bo.getServiceItemIds()[i];
                DisabilityTypeServiceItemBo disabilityTypeServiceItemBo = new DisabilityTypeServiceItemBo();
                disabilityTypeServiceItemBo.setDisabilityType(customer.getDisabilityType());
                disabilityTypeServiceItemBo.setServiceItemId(serviceItemId);
                List<DisabilityTypeServiceItemVo> serviceItemVoList = serviceItemService.queryList(disabilityTypeServiceItemBo);
                serviceItemVoList.forEach(item->{
                    for(int j = 0;j < item.getServiceTimes();j++){
                        //插入任务服务项目明细
                        ServeTaskItemBo taskItem = new ServeTaskItemBo();
                        taskItem.setTaskId(add.getId());
                        taskItem.setServiceItemId(item.getServiceItemId());
                        taskItem.setStatus("0");
                        serveTaskItemService.insertByBo(taskItem);
                    }

                });
            }

            //查询失能类型对应的服务项目
           /* DisabilityTypeServiceItemBo disabilityTypeServiceItemBo = new DisabilityTypeServiceItemBo();
            disabilityTypeServiceItemBo.setDisabilityType(customer.getDisabilityType());
            List<DisabilityTypeServiceItemVo> serviceItemVoList = serviceItemService.queryList(disabilityTypeServiceItemBo);
            serviceItemVoList.forEach(item->{
                for(int i = 0;i < item.getServiceTimes();i++){
                    //插入任务服务项目明细
                    ServeTaskItemBo taskItem = new ServeTaskItemBo();
                    taskItem.setTaskId(add.getId());
                    taskItem.setServiceItemId(item.getServiceItemId());
                    taskItem.setStatus("0");
                    serveTaskItemService.insertByBo(taskItem);
                }

            });*/
        }
        return flag;
    }

    /**
     * 修改服务任务
     */
    @Override
    public Boolean updateByBo(ServeTaskBo bo) {
        ServeTask update = BeanUtil.toBean(bo, ServeTask.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ServeTask entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除服务任务
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 插入月度任务
     * @param month
     */
    @Override
    public void insertMonthTask(String month) {
        var localDate = LocalDate.now();
        Date beginDate = null;
        Date endDate = null;
        ZoneId zone = ZoneId.systemDefault();
        if(StringUtils.isEmpty(month)){
            //如果没有传递月份，那么默认生成下个月的
            beginDate = Date.from(localDate.with(TemporalAdjusters.firstDayOfNextMonth()).atStartOfDay().atZone(zone).toInstant());
            endDate =  Date.from(localDate.plus(1, ChronoUnit.MONTHS).with(TemporalAdjusters.lastDayOfMonth()).atStartOfDay().atZone(zone).toInstant());
        }else{
            beginDate = Date.from(localDate.with(TemporalAdjusters.firstDayOfMonth()).atStartOfDay().atZone(zone).toInstant());
            endDate = Date.from(localDate.with(TemporalAdjusters.lastDayOfMonth()).atStartOfDay().atZone(zone).toInstant());
        }

        //查找所有服务人员
        SysUser queryUser = new SysUser();
        List<SysUser> sysUserList = userService.selectServiceUserList(queryUser);
        for(SysUser u : sysUserList){
            //查询服务对象
            CustomerBo queryCustomer = new CustomerBo();
            queryCustomer.setUserId(u.getUserId());
            List<CustomerVo> customerList = customerService.queryList(queryCustomer);
            for(CustomerVo c : customerList){
                ServeTaskBo taskBo = new ServeTaskBo();
                taskBo.setUserId(u.getUserId());
                taskBo.setCustomerId(c.getId());
                taskBo.setBeginTime(beginDate);
                taskBo.setEndTime(endDate);
                //设置员工姓名
                taskBo.setUserName(u.getNickName());
                //设置任务状态为未开始
                taskBo.setStatus("0");

                ServeTask add = BeanUtil.toBean(taskBo, ServeTask.class);
                validEntityBeforeSave(add);
                boolean flag = baseMapper.insert(add) > 0;
                if (flag) {
                    //查询失能类型对应的服务项目
                    DisabilityTypeServiceItemBo disabilityTypeServiceItemBo = new DisabilityTypeServiceItemBo();
                    disabilityTypeServiceItemBo.setDisabilityType(c.getDisabilityType());
                    List<DisabilityTypeServiceItemVo> serviceItemVoList = serviceItemService.queryList(disabilityTypeServiceItemBo);
                    serviceItemVoList.forEach(item->{
                        for(int i = 0;i < item.getServiceTimes();i++){
                            //插入任务服务项目明细
                            ServeTaskItemBo taskItem = new ServeTaskItemBo();
                            taskItem.setTaskId(add.getId());
                            taskItem.setServiceItemId(item.getServiceItemId());
                            taskItem.setStatus("0");
                            serveTaskItemService.insertByBo(taskItem);
                        }
                    });
                }
            }
        }
    }

    @Override
    public int getServiceCount() {
        return baseMapper.selectCount(new LambdaQueryWrapper<ServeTask>().eq(ServeTask::getStatus, "2")).intValue();
    }

    @Override
    public boolean insertLifaTask( ) {
        CustomerBo customerBo = new CustomerBo();
        List<CustomerVo> customerVoList = this.customerService.queryList(customerBo);
        customerVoList.forEach(c->{
            ServeTaskBo bo = new ServeTaskBo();
            bo.setUserId(1621399601530609665l);
            bo.setUserName(userService.selectUserById(bo.getUserId()).getNickName());
            bo.setCustomerId(c.getId());
            //设置任务状态为未开始
            bo.setStatus("0");
            ServeTask add = BeanUtil.toBean(bo, ServeTask.class);
            validEntityBeforeSave(add);
            boolean flag = baseMapper.insert(add) > 0;
            if (flag) {
                //插入任务服务项目明细
                ServeTaskItemBo taskItem = new ServeTaskItemBo();
                taskItem.setTaskId(add.getId());
                taskItem.setServiceItemId(4l);
                taskItem.setStatus("0");
                serveTaskItemService.insertByBo(taskItem);
            }
        });
        return true;
    }
}
